$(function () {
    obj.init();
});

var obj = new function () {
    'use strict';
    return {
        applyList: null,
        dgState: 'close',
        iId: 0,
        params: {
            schoolId: null,
            iSchoolId: null,
            iStatus: null,
            iType: null,
            iStudId: null,
        },
        init: function () {
            this.applyList = new xhDataGrid($('#list'), 'school_apply/getApply');
            this.applyList.parseToolbar().init();
            xhExtra.disableButton($('#bt_list_del'), 'eu');
            xhExtra.disableButton($('#bt_list_edit'), 'eu');
            xhExtra.disableButton($('#bt_list_log'), 'eu');
            $('#bt_list_apply').menubutton({
                menu: '#menu_apply'
            });
            $('#bt_list_bEstablished').menubutton({
                menu: '#menu_bEstablished'
            });
            $('#bt_list_check').menubutton({
                menu: '#menu_status'
            });
            this.funObj().bindDataGridEvent();
            this.listener();
        },
        listener: function () {
            var $this = this;
            // 绑定搜索事件
            $('#bt_list_search').click(function () {
                $this.funObj().search();
            });
            // 绑定删除事件
            $('#bt_list_del').on('click', function () {
                $this.funObj().deleteApply();
            });
            // 绑定删除事件
            $('#bt_list_edit').on('click', function () {
                $this.funObj().editApply();
            });
            $('#bt_list_applyFor').click(function () {
                $this.funObj().applyFor();
            });
            // 收起
            $('#bt_list_pack').on('click', function () {
                $this.funObj().pack();
            });
            // 展开
            $('#bt_list_expand').on('click', function () {
                $this.funObj().expand();
            });
            // 查看审核意见
            $('#bt_list_log').on('click', function () {
                $this.funObj().applyLog();
            });
        },
        funObj: function () {
            var $this = this;
            return {
                bindDataGridEvent: function () {
                    //加载完毕
                    $this.applyList.onLoadSuccess = function (data) {
                        $.each(data['rows'],function (index,row) {
                            if((row['iType']==3||row['iType']==4)&&!row['sAttachmentUrl']){
                                $this.applyList.command('getExpander',index).parent().hide().after('<div style="width: 24px;"></div>');
                            }
                        });
                        if ($this.dgState == 'open') {
                            $this.funObj().expand();
                        } else if ($this.dgState == 'close') {
                            $this.funObj().pack();
                        }
                        $('.images').viewer();//设置图片点击放大
                    };
                    $this.applyList.onCheck = function (rowIndex, rowData) {
                        if ($this.iId == rowData['iId']) {
                            $this.iId = 0;
                            $this.applyList.command('unselectRow', rowIndex);
                            $('#bt_list_del').setButtonDisable('eu');//编辑enable
                            $('#bt_list_edit').setButtonDisable('eu');//编辑enable
                            $('#bt_list_log').setButtonDisable('eu');//删除enable
                            return false;
                        } else {
                            $this.iId = rowData['iId'];
                            $('#bt_list_log').setButtonEnable('eu');//编辑enable
                            $('#bt_list_edit').setButtonEnable('eu');//编辑enable
                            $('#bt_list_del').setButtonEnable('eu');//删除enable
                        }
                    },
                        $this.applyList.command({
                            view: detailview,
                            detailFormatter: function (index, row) {
                                var str = '<div class="ddv" style="padding:5px 0;overflow: auto;"><table style="width: 100%;height: 100%" >';
                                if (row['iTypeExpansion'] != 0) {
                                    str += '<div style="margin-bottom: 10px;"><b>申请详情:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 30px;">' + row['iTypeExpansion'] + '</span></div>';
                                }
                                if(row['iType'] == 6){
                                    str += '<div style="margin-bottom: 10px;"><b>家长姓名:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 5px;">' + row['sLeadName'] + '</span>'+'<b style="margin-left: 30px;">职务:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 5px;">'+row['sLeadPosition']+'</span>'+'<b style="margin-left: 30px;">联系电话:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 5px;">'+row['sLeadPhone']+'</span></div>';
                                }

                                if(row['iType'] == 7){
                                    str += '<div style="margin-bottom: 10px;"><b>缴费状态:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 30px;">' + row['iPayStateName'] + '</span></div>';
                                }
                                if(row['iType'] == 8){
                                    str += '<div style="margin-bottom: 10px;"><b>单位:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 5px;">' + row['sLeadCompany'] + '</span>'+'<b style="margin-left: 30px;">职务:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 5px;">'+row['sLeadPosition']+'</span>'+'<b style="margin-left: 30px;">联系电话:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 5px;">'+row['sLeadPhone']+'</span></div>';
                                }
                                if(row['iType'] == 9){
                                    str += '<div style="margin-bottom: 10px;"><b>账号:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 5px;">' + row['sAccountNum'] + '</span>'+'<b style="margin-left: 30px;">身份证号码:</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 5px;">'+row['sIdentityNum']+'</span></div>';
                                }
                                if (row['sAttachmentUrl']) {
                                    var key = Object.keys(row['sAttachmentUrl']);
                                    // var val = Object.values(row['sAttachmentUrl']);

                                    var val = Object.keys(row['sAttachmentUrl']).map(function(key) {
                                        return row['sAttachmentUrl'][key];
                                    });

                                    var text = '';
                                    text += '<tr style="height:150px"  class="imgList" nodeId="' + row['iId'] + '">';
                                    for (var j = 0, len = key.length; j < len; j++) {
                                        switch (key[j]) {
                                            case 'tch_img':
                                                key[j] = '教师证';
                                                break;
                                            case 'relation_img':
                                                key[j] = '出生证/户口本';
                                                break;
                                            case 'iDevCost':
                                                key[j] = '设备费';
                                                break;
                                            case 'iSerCost':
                                                key[j] = '服务费';
                                                break;
                                            case 'family_img':
                                                key[j] = '家庭贫困证明';
                                                break;
                                            case 'stud_img':
                                                key[j] = '学生贫困证明';
                                                break;
                                            case 'borrow_img':
                                                key[j] = '平板借用协议';
                                                break;
                                            case 'finance_img':
                                                key[j] = '财务签报';
                                                break;
                                            case 'leader_img':
                                                key[j] = '学校领导证明';
                                                break;
                                            case 'grant_img':
                                                key[j] = '平板发放附件';
                                                break;
                                        }
                                        if (val[j] != "") {
                                            var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
                                            if (reg.test(val[j])) {
                                                text += '<td colspan="2" style="border: 0px;float: left"><div style="text-align: left;margin-left: 9px;position: relative"><span style="position:absolute;top:108px;color:gray;text-align:center;width: 100%;">(' + key[j] + ')</span>&nbsp;&nbsp;&nbsp;&nbsp;' + timeLine.showAll(val[j] + ',', row['iId'], '', false) + '</div>&nbsp;&nbsp;&nbsp;&nbsp;</td>';
                                            } else {
                                                text += '<div style="text-align: left;margin-left: 12px;"><b>' + key[j] + ':</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 30px;">' + val[j] + '</span></div>&nbsp;&nbsp;&nbsp;&nbsp;';
                                            }
                                        }
                                    }
                                    text += '</tr>';
                                    str += '<div style="margin-bottom: 10px;"><b>相关附件:</b>&nbsp;&nbsp;&nbsp;&nbsp;' + text + '</div>';
                                }
                                str += '</table></div>';
                                return str;
                            },
                            onExpandRow: function (index, row) {
                                var ddv = $this.applyList.command('getRowDetail', index).find('div.ddv');
                                ddv.panel({
                                    width: 800,
                                    border: false,
                                    cache: false,
                                    onLoad: function () {
                                        $this.applyList.command('fixDetailRowHeight', index);
                                        $this.applyList.command('fixDetailRowWidth', index);
                                    }
                                });
                                $this.applyList.command('fixDetailRowHeight', index);
                            }
                        });
                },

                // 生成申请表单
                addApply: function (iType, bEstablished) {
                    var titles = '';
                    var height = '';
                    switch (iType) {
                        case 1:
                            titles = '申请教师子女';
                            height = 350;
                            break;
                        case 2:
                            titles = '申请贫困生';
                            height = 380;
                            break;
                        case 3:
                            titles = '申请重新购买';
                            height = 330;
                            break;
                        case 4:
                            titles = '申请缴费凭证丢失';
                            height = 330;
                            break;
                        case 5:
                            titles = '学校领导';
                            height = 330;
                            break;
                        case 6:
                            titles = '领导子女';
                            height = 330;
                            break;
                        case 7:
                            titles = '平板发放';
                            height = 330;
                            break;
                        case 8:
                            titles = '校外领导';
                            height = 330;
                            break;
                        case 9:
                            titles = '新增学生';
                            height = 330;
                            break;
                        case 10:
                            titles = '申请平板租用';
                            height = 330;
                            break;
                    }
                    $this.funObj().initMenuButton();
                    window.top.xhTop.createNewTab(titles, 'school_apply/addStudentApply?iType=' + iType+'&bEstablished='+bEstablished, true);
                },

                // 生成申请表单
                editApply: function () {
                    var id = $this.iId;
                    if (!id) {
                        window.top.xhTop.showError('请选择要审批的申请！');
                        return false;
                    }
                    var rowData = $this.applyList.command('getSelected');
                    var iType = rowData.iType;
                    var titles = '';
                    var height = '';
                    switch (parseInt(iType)) {
                        case 1:
                            titles = '编辑教师子女申请('+rowData.iId+')';
                            height = 350;
                            break;
                        case 2:
                            titles = '编辑贫困生申请('+rowData.iId+')';
                            height = 380;
                            break;
                        case 3:
                            titles = '编辑重新购买申请('+rowData.iId+')';
                            height = 330;
                            break;
                        case 4:
                            titles = '编辑缴费凭证丢失申请('+rowData.iId+')';
                            height = 330;
                            break;
                        case 5:
                            titles = '编辑学校领导申请('+rowData.iId+')';
                            height = 330;
                            break;
                        case 6:
                            titles = '编辑领导子女('+rowData.iId+')';
                            height = 330;
                            break;
                        case 7:
                            titles = '编辑平板发放('+rowData.iId+')';
                            height = 330;
                            break;
                        case 8:
                            titles = '编辑校外领导申请('+rowData.iId+')';
                            height = 330;
                            break;
                        case 9:
                            titles = '新增学生';
                            height = 330;
                            break;
                    }
                    $this.funObj().initMenuButton();
                    window.top.xhTop.createNewTab(titles, 'school_apply/addStudentApply?iId=' + id+'&iType='+iType, true);
                },

                // 查找
                search: function () {
                    var key = xhExtra.getValue($('#list_search'));
                    var type = $('#list_type').combobox('getValue');
                    var status = $('#list_status').combobox('getValue');
                    $this.applyList.reload({key: key, type: type, status: status});
                },

                // 审核
                changeStatus: function (status) {
                    var id = $this.iId;
                    if (!id) {
                        window.top.xhTop.showError('请选择要审批的申请！');
                        return false;
                    }
                    var oldStatus = $this.applyList.getSelectValue('iStatus');
                    var type = $this.applyList.getSelectValue('iType');
                    var sStudName = $this.applyList.getSelectValue('sStudName');
                    var sAccountNum = $this.applyList.getSelectValue('sAccountNum');
                    var sIdentityNum = $this.applyList.getSelectValue('sIdentityNum');
                    if (status == 1 && oldStatus == 3) {
                        window.top.xhTop.showModal({
                            title: '请填写审批意见',
                            content: xhTool.getFrameString('school_apply/financeApproval', {status: status, id: id},350),
                            button: '提交',
                            size: 'sm',
                            width: '650',
                            backClose: true
                        });
                    } else if(type == 9 && oldStatus == 1) {
                        if(status == 1) {
                            var html ='<p style="font-size: 14px;text-align: left">姓名：<span style="margin-right:30px; color: #008aff">'+sStudName+'</span>'+'账号：<span style="margin-right:10px;color: #008aff">'+sAccountNum+'</span></p>'+'<p style="font-size: 14px;text-align: left">身份证号：<span style="color: #008aff">'+sIdentityNum+'</span></p>'+
                                '<input style="float: left;height: 15px;width: 15px" type="checkbox" name="bCreate" id="bCreate" value="1"> <span style="float: left;margin-left: 5px;font-size: 15px;">账号已创建</span>' +
                                '<textarea type="text" id="comment" class="swal2-textarea" placeholder="审批意见" name="comment" rows = "3" cols = "100"></textarea>';
                        } else {
                            var html = '<p style="font-size: 14px;text-align: left">姓名：<span style="margin-right:30px; color: #008aff">'+sStudName+'</span>'+'账号：<span style="margin-right:10px;color: #008aff">'+sAccountNum+'</span></p>'+'<p style="font-size: 14px;text-align: left">身份证号：<span style="color: #008aff">'+sIdentityNum+'</span></p>'+
                                '<textarea type="text" id="comment" class="swal2-textarea" placeholder="审批意见" name="comment" rows = "3" cols = "100"></textarea>';
                        }

                        window.top.swal({
                            title: '审核',
                            html:html,
                            showCancelButton: true,
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            showLoaderOnConfirm: true,
                            preConfirm: function (opinion) {
                                return new Promise(function (resolve, reject) {
                                    var comment = $('#comment', window.top.document).val();
                                    if(status==1&&!$('#bCreate:checked', window.top.document).val()){
                                        reject('请确认账号已创建！');
                                    } else if(!comment){
                                        reject('审核意见不能为空！');
                                    } else {
                                        xhExtra.ajaxRequest('school_apply/approvalApply', {
                                                id: id,
                                                comment: comment,
                                                result: status
                                            }, {
                                                success: true,
                                                table: $this.applyList,
                                            },
                                            function (res) {
                                                $this.iId = 0;
                                                window.top.xhTop.showSuccess(res.msg);
                                            });
                                    }
                                })
                            }
                        });
                    } else {
                        window.top.swal({
                            text: '请填写审批意见',
                            input: 'textarea',
                            showCancelButton: true,
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            showLoaderOnConfirm: true,
                            preConfirm: function (opinion) {
                                return new Promise(function (resolve, reject) {
                                    if (!opinion) {
                                        reject('审批意见不能为空！');
                                    } else {
                                        xhExtra.ajaxRequest('school_apply/approvalApply', {
                                                id: id,
                                                comment: opinion,
                                                result: status
                                            }, {
                                                success: true,
                                                table: $this.applyList,
                                            },
                                            function (res) {
                                                $this.iId = 0;
                                                window.top.xhTop.showSuccess(res.msg);
                                            });
                                    }
                                })
                            }
                        });
                    }
                },

                // 查看审批意见
                applyLog: function () {
                    if ($this.iId == 0) {
                        window.top.xhTop.showError('请选择要查看的申请!');
                        return false;
                    }

                    var text = '<ul style="width: 90%;margin-left: 8px;">';
                    xhExtra.ajaxRequest('school_apply/getApplyLogById', {id: $this.iId}, {
                        check: true,
                        async: false
                    }, function (datas) {
                        $.each(datas, function (index, data) {
                            if (data.sContent.ifComment == 1) {
                                text += '<li style="list-style:none;padding-left: 20px;border-left: 1px solid #ddd;position: relative;' +
                                    'padding-bottom: 20px;line-height: 24px;"><div>'
                                    + data.tCreateDate
                                    + '</div><div><span style="display: inline-block;color: #fff;padding:4px;padding-top:0;' +
                                    'padding-bottom:0;border-radius: 2px;margin-right: 6px;background: #aaa;">'
                                    + data.sContent.title
                                    + '</span>: '
                                    + data.sContent.userName
                                    + data.sContent.action
                                    + '</div><div><span>审批附言:</span>'
                                    + data.sContent.comment
                                    + '</div><span style="width: 14px;height: 14px;background-color: #ddd;border-radius: 50%; '
                                    + 'position: absolute;display: block; left: -7.5px;top: 0;"></span></li>';
                            } else {
                                text += '<li style="list-style:none;padding-left: 20px;border-left: 1px solid #ddd;position: relative;' +
                                    'padding-bottom: 20px;line-height: 24px;"><div>'
                                    + data.tCreateDate
                                    + '</div><div><span style="display: inline-block;color: #fff;padding:4px;padding-top:0;' +
                                    'padding-bottom:0;border-radius: 2px;margin-right: 6px;background: #aaa;">'
                                    + data.sContent.title
                                    + '</span>: '
                                    + data.sContent.userName
                                    + data.sContent.action
                                    + '</div><span style="width: 14px;height: 14px;background-color: #ddd;border-radius: 50%; '
                                    + 'position: absolute;display: block; left: -7.5px;top: 0;"></span></li>';
                            }
                        });
                    });
                    text += '</ul>';

                    window.top.xhTop.showModal({
                        title: '审批记录',
                        content: '<div id="applylogs" style="width:100%;height: 350px;overflow-y: auto;overflow-x: hidden;">' + text + '</div>',
                        backClose: false,
                        size: 'md',
                    });
                },
                applyFor: function(){
                    var iStudId = $this.applyList.getSelectValue('iStudId');
                    var type = $this.applyList.getSelectValue('iType');
                    if(iStudId == 0) {
                        window.top.xhTop.showError('该学生尚未创建账号！');
                        return false;
                    }
                    if(type != 9) {
                        window.top.xhTop.showError('只有新增学生才能申领哦！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '学生机申领',
                        content: xhTool.getFrameString('device/studentApply', {userId:iStudId}, 340),
                        button: '确认',
                        backClose:false
                    });

                },
                // 删除
                deleteApply: function () {
                    if ($this.iId == 0) {
                        window.top.xhTop.showError('请选择要删除的申请!');
                        return false;
                    }
                    xhExtra.ajaxRequest('school_apply/delApply', {id: $this.iId}, {check: true}, function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        $this.applyList.reload();
                    });
                },

                // 收起
                pack: function () {
                    $this.dgState = 'close';
                    var row = $this.applyList.command("getRows");
                    for (var r = 0; r < row.length; r++) {
                        $this.applyList.command("collapseRow", r);
                    }
                },

                // 展开
                expand: function () {
                    $this.dgState = 'open';
                    var row = $this.applyList.command("getRows");
                    for (var r = 0; r < row.length; r++) {
                        $this.applyList.command("expandRow", r);
                    }
                },
                initMenuButton: function () {
                    $('.menu-shadow').hide();
                    $('#menu_apply').hide();
                    $('#menu_bEstablished').hide();
                    $('#bt_list_bEstablished').removeClass('m-btn-plain-active');
                    $('#bt_list_apply').removeClass('m-btn-plain-active');
                }
            }
        }
    }
};